#include "CLine.h"


/////////////////////////////
// makeLine
//
// Create a line 
/////////////////////////////
void CLine::makeLine(POINT beginning_point , POINT end_point , int t )
{
	begin = beginning_point ;
	end   = end_point       ;

	// We want begin.x < end.x
	if ( begin.x > end.x )
	{
		POINT temp ;

		temp = begin ;
		begin = end ;
		end = temp ;
	}	

	// y = ax + b form
	Seta();
	Setb();

	type = t ;
}

///////////////////////////////
// Seta
//
// Calculate the coefficient a
///////////////////////////////
void CLine::Seta()
{
	// if it is a vertical line 
	if ( end.x == begin.x )
		a = INFINITY ;
	else
		a = (float)( (float)( end.y - begin.y ) / (float)( end.x - begin.x ) )  ;
}

//////////////////////////////
// Setb
//
// Calculate b in y = a*x+ b
//////////////////////////////
void CLine::Setb()
{
	b = ( end.y - ( a * end.x ) ) ;
}

////////////////////////////
// Draw
//
// Draw the line
///////////////////////////
void CLine::Draw( HDC hdc )
{
	if ( type == VISUAL )
	{
	    HPEN pen =  CreatePen(0,0,0x00FF00FF);
		SelectObject(hdc,pen);
	}

		MoveToEx(hdc , begin.x , begin.y , 0);  // Move the pen
		LineTo(  hdc , end.x   , end.y )     ;  // Draw a line

		HPEN pen =  CreatePen(0,0,0x0000FF00);
		SelectObject(hdc,pen);
}

/////////////////////////////
// LineCollision
//
// Check if there is a collision
// between 2 line
//
//////////////////////////////
bool CLine::LineCollision(CLine line)
{
	////////////////////////
	// First Quad Detection
	////////////////////////

	// In X We know that begin.x < end.x && line.begin.x < line.end.x
	if ( ( begin.x < line.begin.x && end.x < line.begin.x ) || ( begin.x > line.end.x && end.x > line.end.x ) )
		return false ;

	// In Y
	if ( ( begin.y < min( line.begin.y , line.end.y ) && end.y < min(line.begin.y,line.end.y ) ) ||
		 ( begin.y > max( line.begin.y , line.end.y ) && end.y > max(line.begin.y,line.end.y ) ) ) 
	return false ;
	
	///////////////////////////////////
	// Really Line collision detection
	///////////////////////////////////

	// if there are parrallel
	if ( Geta() == line.Geta() )
		return false ;

	// Check for the collision point
	float x = ((float)( ( line.Getb() - Getb() ) / ( Geta() - line.Geta() ) ) );
	float y = ( Geta() * x + Getb() ) ;

	// Check if this point is on the segment
	POINT b,e   ; // begin and end
	POINT b2,e2 ;

	b = begin ;
	e = end   ;
	b2 = line.begin ;
	e2 = line.end   ;

    // Check if the collision point is in
	// one of the 2 segments
	if ( ( x >= min( b.x , e.x ) )   && ( x <= max(b.x , e.x ) )   &&
		 ( y >= min( b.y , e.y ) )   && ( y <= max(b.y , e.y ) )   &&
		 ( x >= min( b2.x , e2.x ) ) && ( x <= max(b2.x , e2.x ) ) &&
		 ( y >= min( b2.y , e2.y ) ) && ( y <= max(b2.y , e2.y ) ) ) 
		return true ;

return false ;	
}